#include "AnimationPlayer.h"

AnimationPlayer::AnimationPlayer()
{ 
}

AnimationPlayer::~AnimationPlayer()
{
	std::map<std::string, Animation*>::iterator iter = animations.begin();
	for(; iter != animations.end(); ++iter)
	{
       delete iter->second;
	}
	animations.clear();
}

void AnimationPlayer::playAnimation(std::string name)
	{
       Animation* anim = animations[name];
	   if(anim == currentAnimation)
		   return;

	   currentAnimation = anim;
	   playing = name;
	   frameIndex = 0;
	   time = 0.0f;
	}

void AnimationPlayer::update(float frameTime)
	{
      if(currentAnimation == 0)
		  return;

      time += frameTime;

	  while (time > currentAnimation->getFrameTime())
	  {
         time -= currentAnimation->getFrameTime();
		 if(currentAnimation->getIsLooping())
			 frameIndex = (++frameIndex) % currentAnimation->getFrameCount();
		 else
			 frameIndex = min(++frameIndex, currentAnimation->getFrameCount() - 1);
	  }
	}
	
	void AnimationPlayer::draw(ID3DXSprite* sprite, D3DXVECTOR3 position, D3DXMATRIX transform)
	{
       if(currentAnimation == 0)
		   return;
       
	   D3DXMATRIX currentTransform;
	   sprite->GetTransform(&currentTransform);
	   sprite->SetTransform(&transform);

	   int frameX = (frameIndex + currentAnimation->getStartFrame());
	   frameX *= currentAnimation->getFrameWidth();
	   int frameY = (frameIndex + currentAnimation->getStartFrame());
	   frameY *= currentAnimation->getFrameWidth();
	   frameY %= currentAnimation->getFrameWidth();
	   RECT rect;
	   rect.left = frameX;
	   rect.right = frameX + currentAnimation->getFrameWidth();
	   rect.top = frameY;
	   rect.bottom = frameY + currentAnimation->getFrameHeight();

	   sprite->Draw(currentAnimation->getTexture(), &rect, 0, &position, D3DCOLOR_XRGB(255, 255, 255));
	   sprite->SetTransform(&currentTransform);
	   
	}